/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import path from 'path';

import { FileSet } from '@ohos/hvigor';
import * as fse from 'fs-extra';

import { BuildArtifactConst } from '../../const/build-directory-const.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { checkAppPreloadHintStartupTasksSrcEntry, doObfuscationCheck } from '../../utils/task-util.js';
import { AbstractPackageHar } from '../abstract/abstract-package-har.js';
import { TaskNames } from '../common/task-names.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { ProcessHarArtifacts } from './process-har-artifacts.js';
import { InjectUtil } from '../../utils/inject-util.js';
import { DIRECT_IMPORTEE_CACHE_FILE_NAME } from '@ohos/hvigor-arkts-compose';

/**
 * 打包Har包
 *
 * @since 2021/12/18
 */
export class PackageHar extends AbstractPackageHar {
  protected readonly taskTmpDir: string;
  private readonly _log = OhosLogger.getLogger(PackageHar.name);
  initTaskDepends() {
    this.declareDependsList(ProcessHarArtifacts.name);
  }
  constructor(taskService: TargetTaskService) {
    super(taskService, TaskNames.Task.PACKAGE_HAR);
    this.taskTmpDir = this.getTaskTempDir(this.targetData, undefined, false);
  }

  async beforeAlwaysAction(): Promise<void> {
    await super.beforeAlwaysAction();
    doObfuscationCheck(this.targetService, this._log);
    if (this.targetService.isByteCodeHar() && InjectUtil.isByteCodeHarOptimize()) {
      const importeesPath = this.getImporteesCachePath(DIRECT_IMPORTEE_CACHE_FILE_NAME, 'HarCompileArkTS');
      this.doDevDependencyCheck(importeesPath);
      // bundled场景下，由于把源码HAR编进自身，但却没有收集资源等，需要做全局本地依赖warning
      if (this.targetService.isBundledDependencies()) {
        this.doGlobalLocalDependencyCheck(importeesPath);
      }
    }
  }

  declareInputFiles(): FileSet {
    const fileSet = super.declareInputFiles();
    if (fse.existsSync(this.intermediateTempStartupFilePath)) {
      fileSet.addEntry(this.intermediateTempStartupFilePath);
    }
    return fileSet;
  }

  protected async doTaskAction(): Promise<void> {
    // 检查启动框架配置文件中appPreloadHintStartupTasks srcEntry配置的so在libs下存在
    const baseNativeLibsPath = path.resolve(this.pathInfo.getIntermediatesPatch(), BuildArtifactConst.BASE_NATIVE_LIBS_JSON);
    checkAppPreloadHintStartupTasksSrcEntry(this.intermediateTempStartupFilePath, baseNativeLibsPath, this._log, this.moduleName,
      this.targetService.isBundledDependencies());
    return super.doTaskAction();
  }
}
